import AMISRenderer from '@/components/AMISRenderer';
import {useEffect, useState} from "react";
import {jstCallback} from "@/services/shop";
import {useNavigate} from "react-router-dom";

interface RendererProps {
  schemaApi?: any;
}
const AdminSchema: React.FC<RendererProps> = (props)  => {
  const [schema, setSchema] = useState({} as any);

  const navigate = useNavigate();
  /**
   * 接收页面消息回调
   * @param e
   */
  const receiveMessage = (e:MessageEvent) => {
    const {data} = e;
    console.log(data);
    const {type,data:tokenData} = JSON.parse(data);
    if(type === 'jst'){
      jstCallback(tokenData).then((response)=>{
        console.log('--jstCallback',response)
      })
    }
  }
  useEffect(() => {
    window.addEventListener('message', receiveMessage, false);
    if(props.schemaApi){
      setSchema( {
        type: 'service',
        schemaApi: {
          "method": "get",
          // 根据路径查询页面配置
          "url": props.schemaApi,
          "adaptor":function (payload: {
            data: any; code: number;
          }) {
            console.log('---setSchema--',payload)
            if(payload.code === 401){
              navigate('/login', { replace: true });
            }
            return {
              ...payload,
              code: payload.code,
              data: payload.data!==null?JSON.parse(payload.data):{}
            };
          }
        }
      })
    }
  }, [props.schemaApi]);
  return (
      <AMISRenderer schema={schema}></AMISRenderer>
    );
  };

export default AdminSchema;
